<template>
    <div class="sysset-wrap">
        <flexbox align="flex-start" justify="flex-end">
            <flexbox style="cursor: pointer; margin: 8px 8px 0 0; height: 32px; line-height: 32px" @click="handleSysFilter">
                <SettingOutlined />
                <span style="color: #5a6073; margin-left: 4px">设置</span>
            </flexbox>
            <!-- 滚动条 -->
            <!-- <flexbox class="sysset-radio-group" v-if="showSysList.length">
                <div class="radio-group-arrow" @click="handleLeft" v-if="showArrow">
                    <LeftOutlined />
                </div>
                <div class="group-wrap" ref="groupWrapRef">
                    <a-radio-group v-model:value="selectedSys" button-style="solid" ref="radioGroupRef" @change="radioChange">
                        <a-radio-button :value="null" ref="allSystemRef">全部</a-radio-button>
                        <a-radio-button :value="item.systemId" v-for="item of showSysList" :ref="setSysItemRef(item)" :key="item.systemId"> {{ item.system }} </a-radio-button>
                    </a-radio-group>
                </div>
                <div class="radio-group-arrow" @click="handleRight" v-if="showArrow">
                    <RightOutlined />
                </div>
            </flexbox> -->

            <!-- 展开尖头 -->
            <flexbox class="sysset-radio-group" align="flex-end" v-if="showSysList.length">
                <div class="group-wrap" ref="groupWrapRef">
                    <a-radio-group v-model:value="selectedSys" button-style="solid" ref="radioGroupRef" @change="radioChange">
                        <a-radio-button :value="null" ref="allSystemRef" v-if="isHasSystemOption">全部</a-radio-button>
                        <a-radio-button :value="item.systemId" v-for="item of showSysList" :ref="setSysItemRef(item)" :key="item.systemId">
                            {{ item.system }}
                        </a-radio-button>
                    </a-radio-group>
                </div>
                <flexbox justify="center" style="height: 40px; cursor: pointer; padding-top: 8px" @click="toggleShowMore" v-if="isShowMoreBtn">
                    <a>{{ isShowMore ? '收起' : '展开' }}</a>
                </flexbox>
            </flexbox>
            <div style="margin-top: 6px">
                <slot />
            </div>
        </flexbox>
        <!-- 高级筛选表单 -->
        <sys-transfer ref="sysFilterRef" :list="allSysList" :targetList="showSysList" targetDir="left" @success="getMySystem" />
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { SettingOutlined, LeftOutlined, RightOutlined, DownOutlined } from '@ant-design/icons-vue';
import SysTransfer from '@/components/SysSet/SysTransfer.vue';
import store from '@/store';
import { useMountedAndActivated } from '@/hooks/common/useMountedAndActivated';
import { useEventListener } from '@/hooks/event/useEventListener';
import { computed, defineComponent, ref, unref, reactive, toRefs, nextTick, watch, onMounted, onBeforeUnmount } from 'vue';
export default defineComponent({
    emits: ['success'],
    components: {
        SettingOutlined,
        LeftOutlined,
        RightOutlined,
        SysTransfer,
        DownOutlined
    },
    props: {
        defaultSystem: {
            type: [String, Number],
            default: ''
        },
        isShowSetting: {
            type: Boolean,
            default: true
        },
        // 是否显示全部选项
        isHasSystemOption: {
            type: Boolean,
            default: true
        }
    },
    setup(props, { emit }) {
        const sysFilterRef = ref();
        const radioGroupRef = ref();
        const groupWrapRef = ref();
        const allSystemRef = ref();
        const sysItemRefs: any = reactive({});
        const setSysItemRef = (item) => (el) => {
            sysItemRefs[`system-${item.systemId}`] = el;
        };
        const state = reactive<any>({
            allSysList: [],
            selectedSys: '',
            mySysList: [], //我自己的系统列表
            showArrow: false,
            left: 0,
            isShowMore: false,
            isShowMoreBtn: false
        });
        // 先从自己配置里面找选择展示的系统，如果没有配置过从所有系统里截取前5个（所有系统接口findUserAll）
        const showSysList = computed(() => {
            if (state.mySysList.length) {
                return state.mySysList;
            }
            return state.allSysList.length > 5 ? state.allSysList.slice(0, 5) : state.allSysList;
        });
        // 系统筛选
        const handleSysFilter = () => {
            unref(sysFilterRef).open();
        };
        // 获取我的自定义显示的系统
        const getMySystem = async () => {
            const query = {
                // empId: this.userInfo.employeeDTO.empId,
                empId: store.getters.userInfo.employeeDTO.empId
            };
            const { success, moule } = await api.userCustomModel.findByEmpId(query);
            if (success) {
                // 没有值就获取所有系统，并取前5个显示
                if (moule) {
                    const list = JSON.parse(moule.productRequireSystem) || [];
                    state.mySysList = list.map((item) => ({
                        ...item,
                        checked: false
                    }));
                } else {
                    state.mySysList = [];
                }
                // 之所以放到外面是因为需要将所有系统列表传递给子组件
                getAllSystem();
            }
        };
        // 获取我的所有系统
        const getAllSystem = async () => {
            state.allSysList = store.getters.dicOptions.mySystem.map((item) => ({
                ...item,
                system: item.systemName,
                systemId: item.id,
                checked: false
            }));
        };
        const radioChange = (val) => {
            const key = `system-${val.target.value}`;
            let refDom: any = null;
            if (Reflect.has(sysItemRefs, key)) {
                refDom = sysItemRefs[`system-${val.target.value}`];
            } else {
                refDom = unref(allSystemRef);
            }
            if (state.showArrow) {
                // 滚动到可视区域
                // this.$refs[`system-${val.target.value}`].$el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'center' });
                // 重新计算left的值：偏移量=点击目标元素的宽度+目标元素的左偏移量-外部元素宽度
                state.left = -(refDom.$el.offsetWidth + refDom.$el.offsetLeft - unref(groupWrapRef).clientWidth);
                state.left = state.left > 0 ? 0 : state.left;
                unref(radioGroupRef).$el.style.left = state.left + 'px';
            }
        };
        // 点击左侧按钮，菜单向右滚动
        const handleLeft = () => {
            // 判断菜单是否已经向左偏移
            if (state.left < 0) {
                state.left += 100;
                state.left = state.left > 0 ? 0 : state.left;
                unref(radioGroupRef).$el.style.left = state.left + 'px';
            }
        };
        // 点击右侧按钮，菜单向左滚动
        const handleRight = () => {
            const outerWidth = unref(groupWrapRef).clientWidth;
            const innerWidth = unref(radioGroupRef).$el.clientWidth;
            // 向左偏移量的边界值：内部宽度-外部宽度，超出这个边界值无法继续向左偏移
            if (Math.abs(state.left) + outerWidth < innerWidth) {
                state.left -= 100;
                if (Math.abs(state.left) + outerWidth > innerWidth) {
                    state.left = -(innerWidth - outerWidth);
                }
                unref(radioGroupRef).$el.style.left = state.left + 'px';
            }
        };
        // 自动计算宽度差来确定是否显示左右可移动按钮
        const calcMenuWidth = () => {
            nextTick(() => {
                if (unref(groupWrapRef)) {
                    const outerWidth = unref(groupWrapRef).clientWidth;
                    const innerWidth = unref(radioGroupRef).$el.clientWidth;
                    state.showArrow = outerWidth < innerWidth;
                    //重置left的值
                    if (!state.showArrow) {
                        unref(radioGroupRef).$el.style.left = 0;
                    }
                }
            });
        };
        const toggleShowMore = () => {
            state.isShowMore = !state.isShowMore;
            if (state.isShowMore) {
                unref(groupWrapRef).style.height = 'auto';
                unref(groupWrapRef).style.overflow = 'auto';
            } else {
                unref(groupWrapRef).style.height = '40px';
                unref(groupWrapRef).style.overflow = 'hidden';
            }
        };
        // 初始化回调一次
        watch(
            () => state.selectedSys,
            (n: number | string | null) => {
                const item = state.allSysList.find((item) => item.systemId === n);
                emit('success', n, item);
            }
        );
        watch(
            () => showSysList,
            (n) => {
                //n?.length
                if (n) {
                    if (!props.isHasSystemOption) {
                        if (!state.selectedSys && n) {
                            if (n.value.length) {
                                state.selectedSys = +n.value[0].systemId;
                            }
                        }
                    }
                    // calcMenuWidth();
                    nextTick(() => {
                        if (unref(groupWrapRef)) {
                            if (unref(radioGroupRef).$el.clientHeight > 40) {
                                state.isShowMoreBtn = true;
                                unref(groupWrapRef).style.height = '40px';
                                unref(groupWrapRef).style.overflow = 'hidden';
                            }
                        }
                    });
                }
            },
            { deep: true }
        );
        // 及时刷新
        useMountedAndActivated(getMySystem);

        if (props.defaultSystem) {
            state.selectedSys = +props.defaultSystem;
        } else if (props.isHasSystemOption) {
            state.selectedSys = null;
        }
        useEventListener({
            fn: calcMenuWidth
        });
        return {
            sysFilterRef,
            radioGroupRef,
            groupWrapRef,
            setSysItemRef,
            allSystemRef,
            sysItemRefs,
            showSysList,
            ...toRefs(state),
            handleSysFilter,
            getMySystem,
            getAllSystem,
            radioChange,
            handleLeft,
            handleRight,
            calcMenuWidth,
            toggleShowMore
        };
    }
});
</script>
<style scoped lang="less">
.sysset-wrap {
    .sysset-radio-group {
        flex: 1;
        margin-right: 12px;
        .group-wrap {
            width: 100%;
            position: relative;
            flex: 1;
            display: inline-block;
            min-height: 40px;
            transition: all 1s;
            font-size: 12px;
            ::v-deep(.ant-radio-group) {
                transition: left 0.5s ease;
                // position: absolute;
                white-space: nowrap;
                display: flex;
                flex-wrap: wrap;
                .ant-radio-button-wrapper {
                    margin-left: 1px;
                    margin-right: 8px;
                    margin-top: 8px;
                }
            }
        }
        .radio-group-arrow {
            width: 20px;
            height: 100%;
            color: #ccc;
            text-align: center;
            &:hover {
                cursor: pointer;
                color: #000;
            }
        }
    }
}
</style>